﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using UnityEngine;
namespace EzFrameWork
{
    /// <summary>
    /// 操作数据 读写存R W S 
    /// </summary>
    public class EzDataRWS
    {
        /// <summary>
        /// 保存数据  通过PlayerPrefs
        /// </summary>
        /// <param name="DataKey"></param>
        /// <param name="Data"></param>
        public static void PlayerPrefsSaveData(string DataKey, string Data)
        {
            PlayerPrefs.SetString(DataKey, Data);
        }

        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="DataKey"></param>
        /// <param name="data"></param>
        public static string PlayerPrefsLoadData(string DataKey)
        {
            if (PlayerPrefs.HasKey(DataKey))
            {
                return PlayerPrefs.GetString(DataKey);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 文件读取数据 支持安卓端
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string TxtFileRead(string path, Encoding encoding)
        {   
            string data = string.Empty;
            FileInfo t = new FileInfo(path);
            if (!t.Exists)
            {
                return string.Empty;
            }
            try
            {
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs, encoding);
                data = sr.ReadToEnd();
                sr.Close();
                fs.Close();
            }
            catch (IOException e)
            {
                Debug.LogError("FileRead: " + e.Message);
            }
            return data;
        }

        /// <summary>
        /// 文件写入数据 支持安卓端
        /// </summary>
        /// <param name="path"></param>
        /// <param name="data"></param>
        public static void TxtFileWrite(string path, string data, Encoding encoding)
        {
            try
            {
                FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, encoding);
                sw.WriteLine(data);
                sw.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }
        }

        /// <summary>
        /// 加载图片转换成Texture2D
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        private static IEnumerator LoadPictureToTexture2D(string Url, Action<Texture2D> action)
        {
            using (WWW www = new WWW(Url))
            {
                float t = Time.time;
                yield return www;
                action(www.texture);
                float useT = Time.time - t;
                Debug.Log("加载地址：" + Url + "成功!!   用时：" + useT);
            }
        }
        public static void LoadPictureToTexture2DAsy(string Url, Action<Texture2D> action)
        {
            EzMonoManager.Instance.StartCoroutine(LoadPictureToTexture2D(Url, action));
        }
        
        /// <summary>
        /// 加载Texture2D
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="texture"></param>
        /// <returns></returns>
        private static IEnumerator LoadPicture(string Url, Action<Texture2D> action)
        {
            using (WWW www = new WWW(Url))
            {
                yield return www;
                action(www.texture);
                Debug.Log("加载地址：" + Url + "成功");
            }
        }

        public static void LoadPictureAsy(string Url, Action<Texture2D> action)
        {
            EzMonoManager.Instance.StartCoroutine(LoadPicture(Url, action));
        }

        /// <summary>
        /// 异步读取文本
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        private static IEnumerator LoadText(string Url, Action<string> action)
        {
            using (WWW www = new WWW(Url))
            {
                yield return www;
                action(www.text);
                Debug.Log("加载地址：" + Url + "成功");
            }
        }

        //异步加载文本文件
        public static void LoadTextAsy(string Url, Action<string> action)
        {
            EzMonoManager.Instance.StartCoroutine(LoadText(Url, action));
        }

        /// <summary> 
        /// 将一个object对象序列化，返回一个byte[]         
        /// </summary> 
        /// <param name="obj">能序列化的对象</param>         
        /// <returns></returns> 
        public static byte[] ObjectToBytes(object obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, obj); 
                return ms.GetBuffer();
            }
        }

        /// <summary> 
        /// 将一个序列化后的byte[]数组还原         
        /// </summary>
        /// <param name="Bytes"></param>         
        /// <returns></returns> 
        public static T BytesToObject<T>(byte[] Bytes)
        {
            using (MemoryStream ms = new MemoryStream(Bytes))
            {
                IFormatter formatter = new BinaryFormatter(); 
                return (T)formatter.Deserialize(ms);
            }
        }

        /// <summary>
        /// 将某个路径下的文件转换为byte[]
        /// </summary>
        /// <param name="fileUrl"></param>
        /// <returns></returns>
        public static byte[] GetFileToBytes(string fileUrl)
        {
            FileStream fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);
            byte[] buffur = new byte[fs.Length];
            fs.Read(buffur, 0, buffur.Length);
            fs.Close();
            return buffur;
        }

        /// <summary>
        /// byte[] 转 文件
        /// </summary>
        /// <param name="savePath">要保存到的路径</param>
        /// <param name="bytes"></param>
        public static void BytesToFile(string path, string fileName, byte[] bytes)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string savePath = path + "/" + fileName;
            File.WriteAllBytes(savePath, bytes);
            Debug.Log("文件保存地址: " + savePath);
        }

        /// <summary>
        /// byte[] 转 Texture2D
        /// </summary>
        /// <param name="data">数据流</param>
        /// <param name="W">长</param>
        /// <param name="H">宽</param>
        /// <returns></returns>
        public static Texture2D BytesToTexture2D(byte[] data, int W, int H)
        {
            Texture2D texture2D = new Texture2D(W, H);
            texture2D.LoadImage(data);
            return texture2D;
        }

        /// <summary>
        /// 从本地路径中加载Texture2D
        /// </summary>
        /// <param name="url">路径</param>
        /// <param name="W">长</param>
        /// <param name="H">宽</param>
        /// <returns></returns>
        public static Texture2D LoadTexture2DFromPath(string url, int W, int H)
        {
            byte[] temp = GetFileToBytes(url);
            return BytesToTexture2D(temp, W, H);
        }

        /// <summary>
        /// 根据图片路径 转换成 Spirte 目前只支持PNG格式图片
        /// </summary>
        /// <param name="url">路径</param>
        /// <param name="W">长</param>
        /// <param name="H">宽</param>
        /// <returns></returns>
        public static Sprite LoadSpriteFromPath(string url, int W, int H)
        {
            byte[] pictureData = GetFileToBytes(url);
            return BytesToSprite(pictureData, W, H);
        }

        /// <summary> 
        /// byte[] 转 Spirte
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static Sprite BytesToSprite(byte[] bytes, int W, int H)
        {
            //先创建一个Texture2D对象，用于把流数据转成Texture2D
            Texture2D texture = BytesToTexture2D(bytes, W, H);
            texture.LoadImage(bytes);//流数据转换成Texture2D
                                     //创建一个Sprite,以Texture2D对象为基础
            Sprite sp = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
            return sp;
        }

        public static Sprite Texture2DToSpiret(Texture2D texture2D)
        {
            return Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), Vector2.zero);
        }

        /// <summary>
        /// 解析所有类型的文本文件 包括json txt csv 等 不支持移动端
        /// </summary>
        /// <param name="path">文件名需要带后缀</param>
        /// <returns></returns>
        public static string ReadTextFileToString(string path)
        {
            if (File.Exists(path))
            {
                FileInfo fileInfo = new FileInfo(path);
                StreamReader streamReader = fileInfo.OpenText();
                UnityEngine.Debug.Log("文件读取成功");
                string str = streamReader.ReadToEnd();
                streamReader.Close();               //文件流释放
                streamReader.Dispose();
                return str;
            }
            else
            {
                UnityEngine.Debug.Log("路径或名字错误！！");
                return default(string);
            }
        }

        /// <summary>
        /// 将数据写入文本文件
        /// </summary>
        /// <param name="jsonFilePath"></param>
        /// <param name="lastname"></param>
        /// <param name="data"></param>
        public static void WriteTextToFile(string Path, string jsonFileName, string data)
        {
            string tempPath = Path + "/" + jsonFileName;
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);  //创建文件夹
            }
            if (File.Exists(tempPath))
            {
                File.WriteAllText(tempPath, data);
                UnityEngine.Debug.Log("有文件修改成功");
            }
            else
            {
                FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter m_streamWriter = new StreamWriter(fs, Encoding.UTF8);   //UTF8格式写入
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                m_streamWriter.WriteLine(data);
                m_streamWriter.Flush();
                m_streamWriter.Close();
            }
        }
    }
}

